package cn.maiyar.generator.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.maiyar.common.api.BusinessException;
import cn.maiyar.generator.entity.CustomCode;
import cn.maiyar.generator.entity.CustomDataSource;
import cn.maiyar.generator.service.IDatasourceService;
import cn.maiyar.generator.util.GeneratorUtil;
import cn.maiyar.mybatis.Condition;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import cn.maiyar.web.BaseController;
import cn.maiyar.common.api.Result;
import cn.maiyar.common.entity.Query;
import cn.maiyar.generator.entity.Code;
import cn.maiyar.generator.entity.Datasource;
import cn.maiyar.generator.service.ICodeService;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 控制器
 *
 * @author c.c
 * @since 2020-12-01
 */
@RestController
@AllArgsConstructor
@Api(value = "代码生成", tags = "代码生成")
public class CodeController extends BaseController {

    private ICodeService codeService;

    private IDatasourceService datasourceService;

    /**
     * 详情
     *
     * @param code
     * @return
     */
    @GetMapping("/code/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入code")
    public Result<Code> detail(Code code) {
        Code detail = codeService.getOne(Condition.getQueryWrapper(code));
        return Result.data(detail);
    }

    /**
     * 分页
     */
    @GetMapping("/code/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "codeName", value = "模块名", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "tableName", value = "表名", paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "modelName", value = "实体名", paramType = "query", dataType = "string")
    })
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入code")
    public Result<IPage<Code>> list(@ApiIgnore @RequestParam Map<String, Object> code, Query query) {
        IPage<Code> pages = codeService.page(Condition.getPage(query), Condition.getQueryWrapper(code, Code.class));
        return Result.data(pages);
    }

    /**
     * 新增或修改
     */
    @PostMapping("/code/submit")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "新增或修改", notes = "传入code")
    public Result<?> submit(@Valid @RequestBody Code code) {
        return Result.status(codeService.submit(code));
    }


    /**
     * 删除
     */
    @PostMapping("/code/remove")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "删除", notes = "传入ids")
    public Result<?> remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        return Result.status(codeService.removeByIds(StrUtil.split(ids, StringPool.COMMA)));
    }

    private final GeneratorUtil generatorUtil;

    /**
     * 代码生成
     *
     * @param ids
     * @return
     */
    @PostMapping("/code/generator")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "代码生成", notes = "传入ids")
    public Result<?> genCode(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        List<String> idList = StrUtil.split(ids, StringPool.COMMA);
        Collection<Code> codes = codeService.listByIds(idList);
        codes.forEach(code -> {
            CustomCode customCode = new CustomCode();
            // 设置数据源
            Datasource datasource = datasourceService.getById(code.getDatasourceId());
            if (datasource == null) {
                throw new BusinessException("数据源信息不存在!");
            }
            CustomDataSource customDataSource = new CustomDataSource();
            customDataSource.setName(datasource.getName());
            customDataSource.setDriverName(datasource.getDriverClass());
            customDataSource.setUrl(datasource.getUrl());
            customDataSource.setUsername(datasource.getUsername());
            customDataSource.setPassword(datasource.getPassword());
            customCode.setDataSource(customDataSource);

            customCode.setPackageDir(code.getPackageDir());
            customCode.setSystemName(code.getSystemName());
            customCode.setServiceName(code.getServiceName());
            customCode.setModuleName(code.getModuleName());
            customCode.setParentName(code.getParentName());

            customCode.setHasWrapper(code.getHasWrapper() == 1);
            customCode.setHasSuperEntity(code.getHasSuperEntity() == 1);
            customCode.setIsSwagger(code.getIsSwagger() == 1);
            customCode.setFileOverride(code.getFileOverride() == 1);
            customCode.setAuthor(code.getAuthor());

            customCode.setFieldPrefix(code.getFieldPrefix().split(StringPool.COMMA));
            customCode.setFieldSuffix(code.getFieldSuffix().split(StringPool.COMMA));
            customCode.setTablePrefix(code.getTablePrefix().split(StringPool.COMMA));
            customCode.setTableSuffix(code.getTableSuffix().split(StringPool.COMMA));
            customCode.setExcludeTables(code.getExcludeTables().split(StringPool.COMMA));
            customCode.setIncludeTables(code.getIncludeTables().split(StringPool.COMMA));

            generatorUtil.run(customCode);
        });
        return Result.success("代码生成成功");
    }
}
